<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/9/22
 * Time: 12:27
 * 定时任务
 */
namespace app\api\controller;

use app\common\model\AgentShop;
use app\common\model\BusinessPlan;
use app\common\model\OrderGroup;
use app\common\model\RewardRecord;
use app\common\model\SaleStatistics;
use think\Controller;
use think\Db;
use think\Exception;
use app\admin\model\User as UserModel;
use app\common\model\Order as OrderModel;


class Task extends Controller {
	
	/**
	 * 取消2小时内的不付款订单
	 */
	public function cancelOrder() {
		$time = time() - 7200;
		$orders = Db::name('order')
			->where(['create_time' => ['elt', $time], 'status' => \app\common\model\Order::STATUS_WAIT])
			->field('id, order_no')
			->select();
		
		$str = '================='.date('Y-m-d　H:i:s').'======================'.PHP_EOL;
		if($orders) {
			$model = new \app\common\model\Order();
			foreach ($orders as $order) {
				$res = $model->cancel($order['id'], $model::CANCEL_REASON_TIME);
				if (!$res) {
					$str .= $model->getError() . PHP_EOL;
				}
			}
			$str .= '取消成功'.count($orders).'单';
		} else {
			$str .= '没有超时订单'.PHP_EOL;
		}
		
		echo $str;
	}
	
	
	
	/**
	 * 处理超时的拼团订单
	 */
	public function checkGroupOrder() {
		$str = '================='.date('Y-m-d　H:i:s').'======================'.PHP_EOL;
		$model = new OrderGroup();
		$where = [
			'status' => $model::STATUS_ING,
			'end_time' => ['lt', time()]
		];
		
		
		$groups = $model->where($where)->select();
		if($groups) {
			foreach ($groups as $group) {
				$res = $model->fail($group['id']);
				$str .= $group['id'];
				if($res) {
					$str .= '处理成功';
				} else {
					$str .= '处理失败'.$model->getError();
				}
			}
		} else {
			$str .= '没有超时的团';
		}
		echo $str.PHP_EOL;
	}
	
	
	/**
	 * 检测奖励数量
	 */
	public function checkRewardNumber() {
		
		$str = '================='.date('Y-m-d　H:i:s').'======================'.PHP_EOL;
		$users = Db::name('user')
			->where('sale_number', '>', 0)
			->field('id, level, sale_number, reward_number')
			->select();
		if(!$users) {
			$str .= '没有要统计的数量'.PHP_EOL;
		} else {
			$setting = Db::name('ruleSz')->find();
			if(!$setting) {
				$str .= '没有设置'.PHP_EOL;
			} else {
				$userModel = new \app\admin\model\User();
				$orderModel = new \app\common\model\Order();
				$userModel->startTrans();
				
				foreach ($users as $user) {
					try {
					
				
					switch ($user['level']) {
						case $userModel::LEVEL_USER:
							if($setting['user_sale_number'] > 0 && $setting['user_reward_number'] > 0 && $user['sale_number'] >= $setting['user_sale_number']) {
								//获得的奖励数量
								$number = floor($user['sale_number']/$setting['user_sale_number'])*$setting['user_reward_number'];
								//剩余数量
								$lastNumber = $user['sale_number']%$setting['user_sale_number'];
								//更改用户数量
								$userRes = Db::name('user')->where(['id' => $user['id']])
									->update([
										'sale_number' => $lastNumber,
										'reward_number' => $user['reward_number'] + $number
									]);
								if(!$userRes) {
									throw new Exception('更改用户数量出错');
								}
								//添加订单
								$orderRes = $orderModel->addRewardOrder($user['id'], $number, $setting['reward_goods_id'], $setting['reward_spec_id'], $orderModel::TYPE_REWARD, $userModel::AREA_SZ, '普通用户奖励订单');
								if(!$orderRes) {
									throw new Exception('添加奖励订单出错');
								}
							}
							break;
						case $userModel::LEVEL_PROMOTION:
							if($setting['promotion_sale_number'] > 0 && $setting['promotion_reward_number'] > 0 && $user['sale_number'] >= $setting['promotion_sale_number']) {
								//获得的奖励数量
								$number = floor($user['sale_number']/$setting['promotion_sale_number'])*$setting['promotion_reward_number'];
								//剩余数量
								$lastNumber = $user['sale_number']%$setting['promotion_sale_number'];
								//更改用户数量
								$userRes = Db::name('user')->where(['id' => $user['id']])
									->update([
									'sale_number' => $lastNumber,
									'reward_number' => $user['reward_number'] + $number
								]);
								if(!$userRes) {
									throw new Exception('更改用户数量出错');
								}
								//添加订单
								$orderRes = $orderModel->addRewardOrder($user['id'], $number, $setting['reward_goods_id'], $setting['reward_spec_id'], $orderModel::TYPE_REWARD, $userModel::AREA_SZ, '代言人奖励订单');
								if(!$orderRes) {
									throw new Exception('添加奖励订单出错');
								}
							}
							break;
						case $userModel::LEVEL_SHOP:
							if($setting['shop_sale_number'] > 0 && $setting['shop_reward_number'] > 0 && $user['sale_number'] >= $setting['shop_sale_number']) {
								//获得的奖励数量
								$number = floor($user['sale_number']/$setting['shop_sale_number'])*$setting['shop_reward_number'];
								//剩余数量
								$lastNumber = $user['sale_number']%$setting['shop_sale_number'];
								//更改用户数量
								$userRes = Db::name('user')->where(['id' => $user['id']])
									->update([
										'sale_number' => $lastNumber,
										'reward_number' => $user['reward_number'] + $number
									]);
								if(!$userRes) {
									throw new Exception('更改用户数量出错');
								}
								
								$shopRecordRes = RewardRecord::addRecord($user['id'], $number);
								if(!$shopRecordRes) {
									throw new Exception('添加场景店奖励记录出错');
								}
								
								//找他上级发展中心也给一瓶
								$center = Db::name('agentShop')->alias('as')
									->join('agentShop p', 'as.center_id = p.id', 'left')
									->join('user u', 'p.user_id = u.id', 'left')
									->where(['as.user_id' => $user['id']])
									->field('u.id, u.sale_number, u.reward_number')
									->find();
								if($center && $center['id']) {
									//更改用户数量
									$pRserRes = Db::name('user')->where(['id' => $center['id']])
										->setInc('reward_number', $number);
									if(!$pRserRes) {
										throw new Exception('添加发展中心数量出错');
									}
									
									$pShopRecordRes = RewardRecord::addRecord($center['id'], $number, '场景店奖励', $user['id']);
									if(!$pShopRecordRes) {
										throw new Exception('添加发展中心奖励记录出错');
									}
								}
								
							}
							break;
						case $userModel::LEVEL_WAREHOUSE:
							if($setting['warehouse_sale_number'] > 0 && $setting['warehouse_reward_number'] > 0 && $user['sale_number'] >= $setting['warehouse_sale_number']) {
								//获得的奖励数量
								$number = floor($user['sale_number']/$setting['warehouse_sale_number'])*$setting['warehouse_reward_number'];
								//剩余数量
								$lastNumber = $user['sale_number']%$setting['warehouse_sale_number'];
								//更改用户数量
								$userRes = Db::name('user')->where(['id' => $user['id']])
									->update([
										'sale_number' => $lastNumber,
										'reward_number' => $user['reward_number'] + $number
									]);
								if(!$userRes) {
									throw new Exception('更改用户数量出错');
								}
								
								$shopRecordRes = RewardRecord::addRecord($user['id'], $number);
								if(!$shopRecordRes) {
									throw new Exception('添加场景店奖励记录出错');
								}
							}
							break;
						default:
							$str .= '其它身份不奖励'.PHP_EOL;
					}
						$userModel->commit();
						$str .= '处理完成';
					} catch (Exception $e) {
						$userModel->rollback();
						$str .= $e->getMessage().PHP_EOL;
					}}
			}
		}
		
		echo $str . PHP_EOL;
	}
	
	/**
	 * 检测创业大赛状态
	 */
	public function checkPlanStatus() {
		$model = new BusinessPlan();
		//更改报名时间到的开始
		$startRes = Db::name('businessPlan')
			->where(['status' => $model::STATUS_WAIT, 'start_time' => ['elt', time()]])
			->update(['status' => $model::STATUS_ING]);
		
		//更改到期的为结束
		$overRes = Db::name('businessPlan')
			->where(['status' => $model::STATUS_ING, 'end_time' => ['lt', time()]])
			->update(['status' => $model::STATUS_OVER]);
		
		$str = '================='.date('Y-m-d　H:i:s').'======================'.PHP_EOL;
		$str .= '开始活动数量'.$startRes.';结束活动数量:'.$overRes.PHP_EOL;
		echo $str;
	}
	
	/**
	 * 每个月1号统计战区和发展中心的销量
	 */
	public function statisticsSales() {
		$endTime = strtotime(date('Y-m'));
//		$endTime = strtotime(input('date'));
		$startTime = strtotime('-1 month', $endTime);
		
		$agents = Db::name('agentShop')
			->where(['role' => ['in', [UserModel::LEVEL_CENTER, UserModel::LEVEL_THEATER]]])
			->field('id, role, name')
			->select();
		
		$insertData = [];
		if($agents) {
			foreach ($agents as $agent) {
				// 销售量
				$where = [
					'status' => ['in', [OrderModel::STATUS_SUCCESS, OrderModel::STATUS_SIGN]],
					'create_time' => [
						['egt', $startTime],
						['lt', $endTime]
					]
				];
				
				
				if($agent['role'] == UserModel::LEVEL_CENTER) {
					$field = 'center_id';
				} else {
					$field = 'theater_id';
				}
				$where[$field] = $agent['id'];
				
				$saleNumber = Db::name('order')
					->where($where)
					->sum('number');
				
				//核销数量
				$destoryNumber = Db::name('agentShip')->alias('e')
					->join('agentShop a', 'e.agent_shop_id = a.id','left')
					->where([
						'a.'.$field => $agent['id'],
						'e.create_time' => [
							['egt', $startTime],
							['lt', $endTime]
						]
					])
					->sum('number');
				
				if($saleNumber > 0 || $destoryNumber > 0) {
					$insertData[] = [
						'agent_id' => $agent['id'],
						'number' => $saleNumber,
						'destory_number' => $destoryNumber,
						'month' => $startTime,
						'status' => SaleStatistics::STATUS_WAIT,
						'create_time' => time(),
						'update_time' => time()
					];
				}
			
			}
		}
		
		if($insertData) {
			$res = Db::name('saleStatistics')->insertAll($insertData);
			if(!$res) {
				echo '添加出错';
			}
		}
		
		echo '添加成功';
	}
	
	/**
	 * 签收7天前的订单
	 */
	public function signOrder() {
		$time = strtotime('-15 days');
		$orders = Db::name('order')
			->where(['shipping_time' => ['elt', $time], 'status' => \app\common\model\Order::STATUS_WAIT_SIGN])
			->field('id, order_no')
			->select();
		
		$str = '================='.date('Y-m-d　H:i:s').'======================'.PHP_EOL;
		if($orders) {
			$model = new \app\common\model\Order();
			foreach ($orders as $order) {
				$res = $model->sign($order['id']);
				if (!$res) {
					$str .= $model->getError() . PHP_EOL;
				}
			}
			$str .= '签收成功'.count($orders).'单';
		} else {
			$str .= '没有待签收订单'.PHP_EOL;
		}
		
		echo $str;
	}
	
	public function destoryNumber()
	{
		die;
		//核销数量
		$list = Db::name('agentShip')->alias('e')
			->join('agentShop a', 'e.agent_shop_id = a.id','left')
			->field('e.number, a.role, a.id, a.warehouse_id, a.center_id, a.theater_id')
			->select();
		
		$data = [];
		foreach ($list as $item) {
			if(!isset($data[$item['id']])) {
				$data[$item['id']] = 0;
			}
			
			$data[$item['id']] += $item['number'];
			
			if($item['warehouse_id']) {
				if(!isset($data[$item['warehouse_id']])) {
					$data[$item['warehouse_id']] = 0;
				}
				
				$data[$item['warehouse_id']] += $item['number'];
			}
			
			if($item['center_id']) {
				if(!isset($data[$item['center_id']])) {
					$data[$item['center_id']] = 0;
				}
				
				$data[$item['center_id']] += $item['number'];
			}
			
			if($item['theater_id']) {
				if(!isset($data[$item['theater_id']])) {
					$data[$item['theater_id']] = 0;
				}
				
				$data[$item['theater_id']] += $item['number'];
			}
		}
		
		$agents = AgentShop::all(['id' => ['in', array_keys($data)]]);
		foreach ($agents as $agent) {
//			echo $agent['name'].':'.$data[$agent['id']].'<br>';
			echo 'update fa_agent_shop set destory_number = '.$data[$agent['id']].' where id = '.$agent['id'].';<br>';
		}
		dump($data);
	}
}
